package xml_util

import (
	"bytes"
	"fmt"
	"log"

	"github.com/antchfx/xmlquery"
)

func main() {
	// 假设这是你的XML数据
	xmlData := []byte(`  
<books>  
    <book>  
        <title>Go Programming Language</title>  
        <author>Alan A. A. Donovan</author>  
        <year>2015</year>  
    </book>  
    <book>  
        <title>Learning Go with Tests</title>  
        <author>Brian W. Kernighan</author>  
        <year>2017</year>  
    </book>  
</books>  
`)

	// 解析XML数据
	doc, err := xmlquery.Parse(bytes.NewReader(xmlData))
	if err != nil {
		log.Fatalf("Error parsing XML: %v", err)
	}

	// 执行XPath查询来选取所有<book>元素下的<title>元素
	nodes := xmlquery.Find(doc, "//book/title")

	// 遍历查询结果
	for _, n := range nodes {
		// 获取节点的文本内容
		title := getNodeText(n)
		fmt.Println(title)
	}

	// 输出:
	// Go Programming Language
	// Learning Go with Tests
}

func getNodeText(n *xmlquery.Node) string {
	var buf bytes.Buffer
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		if c.Type == xmlquery.TextNode {
			// 如果节点是文本节点，则将其内容写入缓冲区
			buf.WriteString(c.Data)
		} else if c.Type == xmlquery.ElementNode {
			// 如果节点是元素节点，则递归获取其文本内容
			buf.WriteString(getNodeText(c))
		}
	}
	return buf.String()
}
